package com.echo.neocommunity.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.echo.neocommunity.mapper.DiscussPostMapper;
import com.echo.neocommunity.pojo.Comment;
import com.echo.neocommunity.pojo.DiscussPost;
import com.echo.neocommunity.pojo.MyPage;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.CommentService;
import com.echo.neocommunity.service.DiscussPostService;
import com.echo.neocommunity.service.impl.CommentServiceImpl;
import com.echo.neocommunity.service.impl.DiscussPostServiceImpl;
import com.echo.neocommunity.service.impl.LikeService;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import com.echo.neocommunity.utils.HostHolder;
import com.echo.neocommunity.utils.R;
import com.echo.neocommunity.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller()
@RequestMapping("/discusspost")
public class DiscussPostController {


    @Autowired
    private LikeService likeService;

    @Autowired
    private CommentServiceImpl commentService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private DiscussPostServiceImpl discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private SensitiveFilter filter;

    @GetMapping("/get/all")
    public R getDiscussPost(){
        List<DiscussPost> discussPost = discussPostService.getDiscussPost();
        return R.ok().put("data",discussPost);
    }

    @GetMapping("/get/{pageNum}/{pageSize}")
    public R getDiscussPostPage(@PathVariable("pageNum") int pageNum,@PathVariable("pageSize")int pageSize){
        Page<DiscussPost> page=new Page<>();
        discussPostService.page(page);
        List<DiscussPost> records = page.getRecords();
        long total = page.getTotal();
        long current = page.getCurrent();
        long pages = page.getPages();
        return R.ok().put("data",records).put("total",total).put("current",current).put("pages",pages);
    }


    @PostMapping("/add")
    @ResponseBody
    public R addDiscussPost(String title,String content){
        User user = hostHolder.getUser();
        if(user==null){
            return R.error(403,"你还没有登录哦！");
        }
        DiscussPost discussPost=new DiscussPost();
        discussPost.setCreateTime(new Date());
        discussPost.setStatus(0);
        discussPost.setContent(filter.filterText(HtmlUtils.htmlEscape(content)));
        discussPost.setTitle(filter.filterText(HtmlUtils.htmlEscape(title)));
        discussPost.setUserId(user.getId());
        discussPostService.save(discussPost);
        return R.ok().put("msg","恭喜你，帖子发布成功！");
    }

    @GetMapping("/detail/{id}")
    public String getDiscussPostDetail(@PathVariable("id") int id, Model model,Long current){
        User userNow = hostHolder.getUser();
        QueryWrapper<DiscussPost> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",id);
        DiscussPost post = discussPostService.getOne(queryWrapper);
        model.addAttribute("post",post);
        User user = userService.getUserById(post.getUserId());
        model.addAttribute("user",user);
        long likeCount = likeService.getLikeCount(CommunityConstant.ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeCount",likeCount);
        int likeStatus = likeService.findEntityLikeStatus(userNow.getId(), CommunityConstant.ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeStatus",likeStatus);
        if(current==null || current==0)
            current=(long)1;
        Page<Comment> Ipage=new Page(current,5);
        QueryWrapper<Comment> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("entity_type", CommunityConstant.ENTITY_TYPE_POST).eq("entity_id",post.getId()).orderByDesc("create_time");
        Page<Comment> pageI = commentService.page(Ipage, queryWrapper1);
        List<Comment> records = pageI.getRecords();
        long total = pageI.getTotal();
        long pageCount = pageI.getPages();
        MyPage page=new MyPage();
        page.setPath("/discusspost/detail/"+id);
        page.setPages(pageCount);
        page.setTotal(total);
        page.setCurrent(current);
        List<Map<String,Object>> list=new ArrayList<>();
        if(records!=null){
            for (Comment comment : records) {
                Map<String,Object> map=new HashMap<>();
                map.put("comment",comment);
                likeCount = likeService.getLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                map.put("likeCount",likeCount);
                likeStatus = likeService.findEntityLikeStatus(userNow.getId(), CommunityConstant.ENTITY_TYPE_COMMENT, comment.getId());
                map.put("likeStatus",likeStatus);
                map.put("user",userService.getUserById(comment.getUserId()));
                QueryWrapper<Comment> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("entity_type", CommunityConstant.ENTITY_TYPE_COMMENT).eq("entity_id",comment.getId()).orderByDesc("create_time");
                List<Comment> replays = commentService.list(queryWrapper2);
                List<Map<String,Object>> replayList=new ArrayList<>();
                if(replays!=null){
                    for (Comment replay : replays) {
                        Map<String,Object> rep=new HashMap<>();
                        rep.put("replay",replay);
                        likeCount= likeService.getLikeCount(CommunityConstant.ENTITY_TYPE_COMMENT, replay.getId());
                        rep.put("likeCount",likeCount);
                        likeStatus=likeService.findEntityLikeStatus(userNow.getId(),CommunityConstant.ENTITY_TYPE_COMMENT, replay.getId());
                        rep.put("likeStatus",likeStatus);
                        rep.put("user",userService.getUserById(replay.getUserId()));
                        rep.put("target",null);
                        if(replay.getTargetId()!=0){
                            User target=userService.getUserById(replay.getTargetId());
                            rep.put("target",target);
                        }
                        replayList.add(rep);
                    }
                }
                map.put("replays",replayList);
                QueryWrapper<Comment> queryWrapper3=new QueryWrapper<>();
                queryWrapper3.eq("entity_type", CommunityConstant.ENTITY_TYPE_COMMENT).eq("entity_id",comment.getId());
                int replayCount= (int) commentService.count(queryWrapper3);
                map.put("replaysCount",replayCount);
                list.add(map);
            }
        }
        model.addAttribute("comments",list);
        model.addAttribute("page",page);
        return "/site/discuss-detail";
    }









}
